import axios from "axios";
import { Toast } from "vant";
import { delToken, getToken } from "./storage";
import router from "@/router";

const request = axios.create({
  baseURL: "http://interview-api-t.itheima.net/",
  timeout: 5000,
});

request.interceptors.request.use(
  function (config) {
    const token = getToken();

    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  function (error) {
    return Promise.reject(error);
  }
);

request.interceptors.response.use(
  function (response) {
    return response.data;
  },
  function (error) {
    // 响应拦截器-统一异常处理
    if (error.response) {
      // 💥 401时 表示登录过期，
      if (error.response.status === 401) {
        Toast("登录超时, 请重新登录");
        delToken();
        router.push("/login");
      } else {
        Toast(error.response.data.message);
      }
    } else {
      // 🔔 error不存在代表， 网络不通
      Toast("网络不通,请检查");
    }
    return Promise.reject(error);
  }
);

export default request;
